<template>
  <div class="health-reports-container">
    <el-card class="upload-card">
      <template #header>
        <div class="card-header">
          <span>上传体检报告</span>
        </div>
      </template>
      <el-upload
        class="upload-demo"
        drag
        :action="uploadUrl"
        :headers="uploadHeaders"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
        accept=".pdf"
      >
        <el-icon class="el-icon--upload"><Upload /></el-icon>
        <div class="el-upload__text">
          将PDF文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传PDF格式的体检报告文件，文件大小不超过10MB
          </div>
        </template>
      </el-upload>
    </el-card>

    <el-card class="reports-card">
      <template #header>
        <div class="card-header">
          <span>我的体检报告</span>
        </div>
      </template>
      <el-table :data="reports" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="uploaded_at" label="上传时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.uploaded_at) }}
          </template>
        </el-table-column>
        <el-table-column label="查看报告" width="100">
          <template #default="scope">
            <el-link type="primary" @click="viewReport(scope.row)">查看</el-link>
          </template>
        </el-table-column>
        <el-table-column label="分析状态" width="150">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 'completed'" type="success">{{ scope.row.status_display }}</el-tag>
            <el-tag v-else-if="scope.row.status === 'analyzing'" type="warning">{{ scope.row.status_display }}</el-tag>
            <el-tag v-else-if="scope.row.status === 'failed'" type="danger">{{ scope.row.status_display }}</el-tag>
            <el-tag v-else-if="scope.row.status === 'uploaded'" type="info">{{ scope.row.status_display }}</el-tag>
            <el-tag v-else type="info">{{ scope.row.status_display }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === 'uploaded' || scope.row.status === 'failed'" 
              size="small" 
              type="primary" 
              @click="analyzeReport(scope.row)" 
              :loading="scope.row.analyzing"
            >
              分析
            </el-button>
            <el-button 
              v-if="scope.row.status === 'completed'" 
              size="small" 
              type="success" 
              @click="viewAnalysisResult(scope.row)"
            >
              查看分析结果
            </el-button>
            <el-button 
              v-if="scope.row.status === 'analyzing'" 
              size="small" 
              type="warning" 
              @click="viewAnalysisResult(scope.row)"
              :loading="true"
            >
              正在分析...
            </el-button>
            <el-button size="small" type="danger" @click="deleteReport(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 分析结果对话框 -->
    <el-dialog v-model="dialogVisible" title="分析结果" width="60%">
      <div class="analysis-result" v-loading="analyzing">
        <div class="stream-content" v-html="streamContent"></div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import { useUserStore } from '@/stores/user'
import request from '@/api/request'

// 状态管理
const userStore = useUserStore()
const reports = ref<any[]>([])
const loading = ref(false)
const analyzing = ref(false)
const dialogVisible = ref(false)
const streamContent = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
let eventSource: EventSource | null = null

// 计算属性
const uploadUrl = computed(() => `${import.meta.env.VITE_API_BASE_URL}/health/health-reports/`)
const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${userStore.token}`
}))

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 获取报告列表
const fetchReports = async () => {
  loading.value = true
  try {
    const response: any = await request.get('/health/health-reports/', {
      params: {
        page: currentPage.value,
        page_size: pageSize.value
      }
    })
    reports.value = response.results || response.data || []
    total.value = response.count || (response.data ? response.data.length : 0)
  } catch (error: any) {
    ElMessage.error('获取报告列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 上传前检查
const beforeUpload = (file: File) => {
  const isPDF = file.type === 'application/pdf'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isPDF) {
    ElMessage.error('只能上传PDF文件!')
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!')
  }
  return isPDF && isLt10M
}

// 上传成功处理 - 局部刷新，不刷新整个页面
const handleUploadSuccess = (response: any, file: any) => {
  ElMessage.success('上传成功，正在分析中...')
  
  // 如果是新上传的报告，添加到列表顶部并启动状态轮询
  if (response.report_id) {
    // 创建新的报告对象
    const newReport = {
      id: response.report_id,
      status: 'analyzing',
      status_display: '正在分析',
      analyzing: true,
      uploaded_at: new Date().toISOString(),
      file_path: file.name
    }
    
    // 添加到列表顶部
    reports.value.unshift(newReport)
    
    // 启动状态轮询
    startStatusPolling(response.report_id)
  }
}

// 上传失败处理
const handleUploadError = (error: any) => {
  ElMessage.error('上传失败: ' + (error.message || '未知错误'))
}

// 查看报告 - 直接在新标签页打开PDF
const viewReport = (report: any) => {
  if (report.file_path) {
    // 使用前端端口而不是后端端口
    const pdfUrl = `http://localhost:3000/media/${report.file_path}`
    window.open(pdfUrl, '_blank')
  }
}

// 查看分析结果
const viewAnalysisResult = async (report: any) => {
  dialogVisible.value = true;
  
  // 如果报告正在分析中，启动流式分析
  if (report.status === 'analyzing') {
    await startStreamAnalysis(report.id);
  } else if (report.status === 'completed') {
    // 如果分析已完成，直接显示结果
    streamContent.value = report.analysis_result || '暂无分析结果';
    analyzing.value = false;
  } else {
    // 其他状态显示提示信息
    streamContent.value = '请先进行分析';
    analyzing.value = false;
  }
}

// 分析报告 - 局部更新状态，不刷新整个页面
const analyzeReport = async (report: any) => {
  // 立即更新UI状态为正在分析
  const reportIndex = reports.value.findIndex(r => r.id === report.id);
  if (reportIndex !== -1) {
    reports.value[reportIndex].status = 'analyzing';
    reports.value[reportIndex].status_display = '正在分析';
    reports.value[reportIndex].analyzing = true; // 设置分析中状态
  }
  
  // 首先触发分析任务
  try {
    await request.post(`/health/health-reports/${report.id}/trigger-analysis/`)
    ElMessage.success('分析任务已启动，请稍后查看结果')
    
    // 启动状态轮询，局部更新状态
    startStatusPolling(report.id);
  } catch (error: any) {
    let errorMessage = '无法启动分析任务';
    if (error.response && error.response.data && error.response.data.error) {
      errorMessage = error.response.data.error;
    } else if (error.message) {
      errorMessage = error.message;
    }
    ElMessage.error(errorMessage);
    
    // 任务启动失败，回滚UI状态
    if (reportIndex !== -1) {
      reports.value[reportIndex].status = 'failed';
      reports.value[reportIndex].status_display = '分析失败';
    }
    
    console.error('触发分析任务失败:', error);
    return;
  }
}

// 状态轮询函数 - 用于局部更新报告状态
const startStatusPolling = (reportId: number) => {
  const pollInterval = setInterval(async () => {
    try {
      // 获取报告详情
      const response: any = await request.get(`/health/health-reports/${reportId}/`)
      const updatedReport = response.data || response
      
      // 找到对应的报告索引
      const reportIndex = reports.value.findIndex(r => r.id === reportId)
      if (reportIndex !== -1) {
        // 更新报告状态
        reports.value[reportIndex].status = updatedReport.status
        reports.value[reportIndex].status_display = updatedReport.status_display
        reports.value[reportIndex].analysis_result = updatedReport.analysis_result
        reports.value[reportIndex].analyzing = false
        
        // 如果分析完成或失败，停止轮询
        if (updatedReport.status === 'completed' || updatedReport.status === 'failed') {
          clearInterval(pollInterval)
          
          // 显示完成消息
          if (updatedReport.status === 'completed') {
            ElMessage.success('分析完成')
          } else if (updatedReport.status === 'failed') {
            ElMessage.error('分析失败')
          }
        }
      } else {
        // 如果报告不在列表中，停止轮询
        clearInterval(pollInterval)
      }
    } catch (error) {
      console.error('状态轮询失败:', error)
      // 出错时停止轮询
      clearInterval(pollInterval)
    }
  }, 3000) // 每3秒轮询一次
  
  // 30秒后自动停止轮询（防止无限轮询）
  setTimeout(() => {
    clearInterval(pollInterval)
  }, 30000)
}

// 辅助函数：局部更新报告状态
const updateReportStatus = (reportId: number, status: string) => {
  const reportIndex = reports.value.findIndex(r => r.id === reportId)
  if (reportIndex !== -1) {
    reports.value[reportIndex].status = status
    reports.value[reportIndex].status_display = status === 'completed' ? '分析完成' : 
                                               status === 'failed' ? '分析失败' : 
                                               status === 'analyzing' ? '正在分析' : '已上传'
    reports.value[reportIndex].analyzing = false
    
    // 显示完成消息
    if (status === 'completed') {
      ElMessage.success('分析完成')
    } else if (status === 'failed') {
      ElMessage.error('分析失败')
    }
  }
}

// 开始流式分析 - 使用SSE
const startStreamAnalysis = async (reportId: number) => {
  if (!reportId) return
  
  analyzing.value = true
  streamContent.value = '正在分析中...'
  
  try {
    // 关闭之前的EventSource连接（如果有的话）
    if (eventSource) {
      eventSource.close()
      eventSource = null
    }
    
    // 创建新的EventSource连接
    const url = `${import.meta.env.VITE_API_BASE_URL}/health/health-reports/${reportId}/analysis-stream/`
    
    // 手动添加认证头的EventSource
    eventSource = new EventSource(url)
    
    // 处理接收到的消息
    eventSource.onmessage = (event) => {
      if (event.data === '[DONE]') {
        // 分析完成
        if (eventSource) {
          eventSource.close()
          eventSource = null
        }
        analyzing.value = false
        // 局部更新报告状态为已完成
        updateReportStatus(reportId, 'completed')
      } else {
        try {
          // 解析JSON数据
          const data = JSON.parse(event.data)
          if (data.analysis_result) {
            streamContent.value = data.analysis_result
          }
        } catch {
          // 如果不是JSON格式，直接显示
          streamContent.value = event.data
        }
      }
    }
    
    // 处理错误
    eventSource.onerror = (error) => {
      console.error('SSE连接错误:', error)
      if (eventSource) {
        eventSource.close()
        eventSource = null
      }
      analyzing.value = false
      streamContent.value = '分析过程中发生错误'
    }
  } catch (error: any) {
    ElMessage.error('分析失败')
    console.error(error)
    streamContent.value = '分析失败: ' + (error.message || '未知错误')
    analyzing.value = false
  }
}

// 删除报告
const deleteReport = async (report: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这份体检报告吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await request.delete(`/health/health-reports/${report.id}/`)
    ElMessage.success('删除成功')
    fetchReports()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchReports()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchReports()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchReports()
})

// 组件卸载时关闭SSE连接
onUnmounted(() => {
  if (eventSource) {
    eventSource.close()
    eventSource = null
  }
})
</script>

<style scoped>
.health-reports-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-card {
  margin-bottom: 20px;
}

.reports-card {
  margin-bottom: 20px;
}

.analysis-result {
  min-height: 400px;
}

.stream-content {
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
  min-height: 300px;
  white-space: pre-wrap;
  line-height: 1.6;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>